//
//  ClassifyManageViewController.m
//  LazyCat
//
//  Created by jike on 15/12/28.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "ClassifyManageViewController.h"
#import "AFNetworkHandler.h"
#import "classifyTableViewCell.h"
#import "AddTypeViewController.h"
#import "FeWifiManHub.h"
#import "addViewController.h"

@interface ClassifyManageViewController ()<UITableViewDataSource,UITableViewDelegate,classifyDelegate,backPassdelegate,addBackdelegate,UIAlertViewDelegate>
{
    FeWifiManHub *_loading;
}
@property (nonatomic,strong) UITableView *tableV;//表视图
@property (nonatomic,strong) NSMutableArray *dataArr;//获取数组数组
@property (nonatomic,strong) NSMutableArray *headerArr;//头部显隐数组
@property (nonatomic,strong) NSMutableArray *arr;//
@property (nonatomic,strong) UIView *noNetView;//无网络视图
@property (nonatomic,strong) UIView *noDataView;//无数据视图
@property (nonatomic,assign) NSInteger numSec;//删除产品的id行
@property (nonatomic,assign) NSInteger numRow;//删除产品的id列

@end

@implementation ClassifyManageViewController

-(void)viewWillAppear:(BOOL)animated {
    if (kNetworkNotReachability) {
        [[MessShowView share] showWithMess:@"当前网络不给力"];
        self.noNetView.hidden = NO;
        self.tableV.hidden = YES;
        [_loading dismiss];
        [_loading removeFromSuperview];
    }else {
        self.tableV.hidden = NO;
        self.noNetView.hidden = YES;
    }
}
-(void)AddValue:(NSString *)val {//代理
    if ([val isEqualToString:@"m"]) {
        [self getData];
    }
}
-(void)passValue:(NSString *)val {//代理
    if ([val isEqualToString:@"yesm"]) {//刷新某一行
        [self getData];
    }else if ([val isEqualToString:@"yesn"]) {
        [self getData];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNav:@"分类管理" doBack:YES];
    UIView *lineV= [[UIView alloc]initWithFrame:CGRectMake(0, 63, ScreenWidth, 1)];
    lineV.alpha = 0.2;
    lineV.backgroundColor = [UIColor lightGrayColor];
    UIButton *addClassBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addClassBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [addClassBtn setTitle:@"添加" forState:UIControlStateNormal];
    [addClassBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [addClassBtn addTarget:self action:@selector(addClassify) forControlEvents:UIControlEventTouchUpInside];
    addClassBtn.frame = CGRectMake(ScreenWidth-52, 20+7, 42, 30);
    [self.navBar addSubview:addClassBtn];
    [self.navBar addSubview:lineV];
    [self createTableV];//创建表视图
    [self getData];//获取所有数据
}
-(void)createTableV {//创建表视图
    //第一块表视图
    self.tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64) style:UITableViewStyleGrouped];
    self.tableV.backgroundColor = BackColor;
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    [self.view addSubview:self.tableV];
    self.tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableV registerClass:[classifyTableViewCell class] forCellReuseIdentifier:@"Cell"];//注册
    //第二块加载视图
    if ([self.isFromV isEqualToString:@"100"]) {//从分类页面不需要loading
        
    }else {//从产品上下架页面需要loading
        _loading = [[FeWifiManHub alloc] initWithView:self.view withMode:FeWifiManHubModeOnlyLoader];
        [self.view addSubview:_loading];
        [_loading show];
    }
    //第三块无网络视图
    self.noNetView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64)];
    self.noNetView.hidden = YES;
    self.noNetView.backgroundColor = [UIColor colorWithRed:242 / 255.0 green:243 / 255.0 blue:247 / 255.0 alpha:1];
    [self.view addSubview:self.noNetView];
    UIImageView *netImg = [[UIImageView alloc] initWithFrame:CGRectMake((ScreenWidth-100)/2, 60, 100, 90)];
    netImg.image = [UIImage imageNamed:@"无网络_r1_c1"];
    [self.noNetView addSubview:netImg];
    UILabel *netFail = [[UILabel alloc] initWithFrame:CGRectMake(0, 170, ScreenWidth, 20)];
    netFail.text = @"网络请求失败";
    netFail.textAlignment = NSTextAlignmentCenter;
    netFail.font = [UIFont systemFontOfSize:16];
    [self.noNetView addSubview:netFail];
    UIButton *refresh = [[UIButton alloc] initWithFrame:CGRectMake((ScreenWidth-120)/2, 200, 120, 40)];
    [refresh setImage:[UIImage imageNamed:@"无网络_r3_c2 下午4.23.04"] forState:UIControlStateNormal];
    refresh.adjustsImageWhenHighlighted = NO;
    [self.noNetView addSubview:refresh];
    [refresh addTarget:self action:@selector(refreshV) forControlEvents:UIControlEventTouchUpInside];//刷新
    //第四块无数据视图
    self.noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64)];
    self.noDataView.hidden = YES;
    self.noDataView.backgroundColor = BackColor;
    [self.view addSubview:self.noDataView];
    UIImageView *noDataIV = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth-80)/2, 70, 80, 80)];
    noDataIV.image = [UIImage imageNamed:@"wufenlei"];
    [self.noDataView addSubview:noDataIV];
    UILabel *nodataL = [[UILabel alloc]initWithFrame:CGRectMake(0, 165, ScreenWidth, 25)];
    nodataL.text = @"抱歉,您暂时还没有分类";
    nodataL.textAlignment = NSTextAlignmentCenter;
    nodataL.font = [UIFont systemFontOfSize:16];
    nodataL.textColor = [UIColor lightGrayColor];
    [self.noDataView addSubview:nodataL];
}
-(void)addClassify {//跳到新增分类的页面
    addViewController *addVC = [[addViewController alloc]init];
    addVC.delegate = self;
    addVC.isFrom = @"200";
    if (self.dataArr.count > 0) {
        addVC.HeadArr = self.dataArr;
    }else {
        
    }
    [self.navigationController pushViewController:addVC animated:YES];
}
-(void)refreshV{//刷新
    if (kNetworkNotReachability) {
        [[MessShowView share] showWithMess:@"当前网络不给力"];
        self.noNetView.hidden = NO;
        self.tableV.hidden = YES;
    }else {
        self.tableV.hidden = NO;
        self.noNetView.hidden = YES;
        [self getData];//获取数据
    }
}
-(void)getData {//获取数据
    if (kNetworkNotReachability) {
        [[MessShowView share] showWithMess:@"当前网络不给力"];
        [_loading dismiss];
        [_loading removeFromSuperview];
    }
    NSString *url = [NSString stringWithFormat:classifyUrl,[AppData share].username];
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        NSDictionary *dict = result;
        NSString *r = dict[@"r"];
        if ([r isEqualToString:@"T"]) {
            self.dataArr = [NSMutableArray array];
            self.dataArr = dict[@"categories"];
//            self.headerArr = [NSMutableArray array];//头部显隐数组
//            NSMutableArray *topHeaderArr = [NSMutableArray arrayWithArray:[NSUserDefualManager getValueByKey:@"top"]];
//            if (topHeaderArr.count == 0) {
//                for (int i = 0; i < self.dataArr.count; i++) {
//                    [self.headerArr addObject:@"0"];
//                }
//            }else {
//                self.headerArr = [NSMutableArray arrayWithArray:topHeaderArr];
//            }
            if (self.dataArr.count > 0) {
                self.tableV.hidden = NO;
                self.noDataView.hidden = YES;
                [self.tableV reloadData];
            }else {
                self.tableV.hidden = YES;
                self.noDataView.hidden = NO;
            }
            [_loading dismiss];
            [_loading removeFromSuperview];
        }else {
            [_loading dismiss];
            [_loading removeFromSuperview];
        }
    }];
    [_loading dismiss];
    [_loading removeFromSuperview];
}
//uitableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *arr = [self.dataArr[section] objectForKey:@"childrencategory"];
//    NSString *open = [NSString stringWithFormat:@"%@",self.headerArr[section]];
//    BOOL isOpen;
//    if ([open isEqualToString:@"0"]) {
//        isOpen = NO;
//    }else {
//        isOpen = YES;
//    }
//    NSInteger count = isOpen?arr.count:0;
//    return count;
    return arr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    classifyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" ];
    cell.delegate = self;
    cell.duiIV.hidden = YES;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSArray *arr = [self.dataArr[indexPath.section] objectForKey:@"childrencategory"];
    NSString *secondIsAdvance = [arr[indexPath.row] objectForKey:@"isactived"];//子分类是否启用
    if ([secondIsAdvance isEqualToString:@"0"]) {
        cell.nameL.text = [NSString stringWithFormat:@" ∟ %@(未启用)",[arr[indexPath.row] objectForKey:@"categoryname"]];
    }else {
        cell.nameL.text = [NSString stringWithFormat:@" ∟ %@",[arr[indexPath.row] objectForKey:@"categoryname"]];
    }
    cell.backgroundColor = [UIColor colorWithRed:248/255.0 green:248/255.0 blue:248/255.0 alpha:1.0];
    if (indexPath.row == arr.count - 1) {
        cell.lineV.frame = CGRectMake(0, 39, ScreenWidth, 1);
    }else {
        cell.lineV.frame = CGRectMake(15, 39, ScreenWidth-15, 1);
    }
    return cell;
}
-(void)tableViewCell:(classifyTableViewCell *)cell btn:(UIButton *)btn {//按钮代理
    NSIndexPath *indexPath = [self.tableV indexPathForCell:cell];
    if (btn.tag == 100 || btn.tag == 300) {
        NSLog(@"编辑");
        AddTypeViewController *addTyVC = [[AddTypeViewController alloc]init];
        addTyVC.typeLevel = @"1";
        addTyVC.delegate = self;
        addTyVC.dict = self.dataArr[indexPath.section];
        addTyVC.rowNum = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
        addTyVC.fuArr = self.dataArr;
        [self.navigationController pushViewController:addTyVC animated:YES];
    }else {
        NSLog(@"删除");
        self.numSec = indexPath.section;
        self.numRow = indexPath.row;
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"是否删除该产品" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
        alert.delegate = self;
        alert.tag = 200;
        [alert show];
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {//点击方法
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {//创建头部视图
    UIView *headerV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
    headerV.backgroundColor = [UIColor whiteColor];
    UILabel *classL = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, ScreenWidth-70, 50)];
    classL.textAlignment = NSTextAlignmentLeft;
    classL.font = [UIFont systemFontOfSize:16];
    classL.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0];
    NSString *firstIsAdvance = [self.dataArr[section] objectForKey:@"isactived"];//父分类是否启用
    if ([firstIsAdvance isEqualToString:@"0"]) {
        classL.text = [NSString stringWithFormat:@"%@(未启用)",[self.dataArr[section] objectForKey:@"categoryname"]];
    }else {
        classL.text = [NSString stringWithFormat:@"%@",[self.dataArr[section] objectForKey:@"categoryname"]];
    }
    [headerV addSubview:classL];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, ScreenWidth-100, 50);
    btn.tag = section;
    [btn addTarget:self action:@selector(isOpen:) forControlEvents:UIControlEventTouchUpInside];//点击打开单元格
    [headerV addSubview:btn];
    UIView *lineV = [[UIView alloc]initWithFrame:CGRectMake(0, 49, ScreenWidth, 1)];
    lineV.alpha = 0.2;
    lineV.backgroundColor = [UIColor lightGrayColor];
    [headerV addSubview:lineV];
    /*********************************/
    UIButton *editBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    editBtn.frame = CGRectMake(ScreenWidth-60, 18, 15, 15);
    editBtn.tag = section + 100;
    [editBtn setBackgroundImage:[UIImage imageNamed:@"editClassify"] forState:UIControlStateNormal];
    [editBtn addTarget:self action:@selector(editTop:) forControlEvents:UIControlEventTouchUpInside];
    UIButton *replaceBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    replaceBtn1.frame = CGRectMake(ScreenWidth-70, 5, 35, 40);
    replaceBtn1.tag = section + 100;
    [replaceBtn1 addTarget:self action:@selector(editTop:) forControlEvents:UIControlEventTouchUpInside];
    UIButton *delateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    delateBtn.frame = CGRectMake(ScreenWidth-30, 18, 15, 15);
    delateBtn.tag = section + 10;
    [delateBtn setBackgroundImage:[UIImage imageNamed:@"delateClassify"] forState:UIControlStateNormal];
    [delateBtn addTarget:self action:@selector(delaTop:) forControlEvents:UIControlEventTouchUpInside];
    UIButton *replaceBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    replaceBtn2.frame = CGRectMake(ScreenWidth-30, 5, 30, 40);
    replaceBtn2.tag = section + 10;
    [replaceBtn2 addTarget:self action:@selector(delaTop:) forControlEvents:UIControlEventTouchUpInside];
    [headerV addSubview:editBtn];
    [headerV addSubview:delateBtn];
    [headerV addSubview:replaceBtn1];
    [headerV addSubview:replaceBtn2];
    /*********************************/
    return headerV;
}
-(void)editTop:(UIButton *)sender {//头部点击事件编辑
    NSLog(@"编辑");
    AddTypeViewController *addTyVC = [[AddTypeViewController alloc]init];
    addTyVC.typeLevel = @"0";
    addTyVC.delegate = self;//设置代理
    addTyVC.dict = self.dataArr[sender.tag - 100];
    [self.navigationController pushViewController:addTyVC animated:YES];
}
-(void)delaTop:(UIButton *)sender {//头部点击事件删除
    NSLog(@"删除");
    self.numSec = sender.tag-10;
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"是否删除该类产品" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
    alert.delegate = self;
    alert.tag = 100;
    [alert show];
}
-(void)isOpen:(UIButton *)btn {//点击打开单元格
    NSLog(@"点击头部");
//    NSString *str = self.headerArr[btn.tag];
//    if ([str isEqualToString:@"0"]) {
//        [self.headerArr replaceObjectAtIndex:btn.tag withObject:@"1"];
//        [NSUserDefualManager storageValue:self.headerArr forKey:@"top"];
//        [self.tableV reloadData];
//    }else {
//        [self.headerArr replaceObjectAtIndex:btn.tag withObject:@"0"];
//        [NSUserDefualManager storageValue:self.headerArr forKey:@"top"];
//        [self.tableV reloadData];
//    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {//单元格高度
    return 40;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {//头部视图高度
    return 50;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {//尾部视图高度
    return 0.01;
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 100) {
        if (buttonIndex == 1) {
            NSString *identify = [self.dataArr[self.numSec] objectForKey:@"categoryid"];
            NSString *url = [NSString stringWithFormat:delateClassifyUrl,identify];
            [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
                NSDictionary *dict = result;
                NSString *r = dict[@"r"];
                if ([r isEqualToString:@"T"]) {
                    [[MessShowView share] showWithMess:@"删除成功" login:YES];
                    [self.dataArr removeObjectAtIndex:self.numSec];
                    if (self.dataArr.count > 0) {
                        self.noDataView.hidden = YES;
                        self.tableV.hidden = NO;
                        [self.delegate successEditStr:@"T"];
                        [self.tableV reloadData];
                    }else {
                        self.noDataView.hidden = NO;
                        self.tableV.hidden = YES;
                    }
                }else {
                    [[MessShowView share] showWithMess:dict[@"m"] login:NO];
                }
            }];
        }
    }else if(alertView.tag == 200){
        if (buttonIndex == 1) {
            NSMutableArray *arr = [self.dataArr[self.numSec] objectForKey:@"childrencategory"];
            NSString *identify = [arr[self.numRow] objectForKey:@"categoryid"];
            NSString *url = [NSString stringWithFormat:delateClassifyUrl,identify];
            [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
                NSDictionary *dict = result;
                NSString *r = dict[@"r"];
                if ([r isEqualToString:@"T"]) {
                    [[MessShowView share] showWithMess:@"删除成功" login:YES];
                    [arr removeObjectAtIndex:self.numRow];
                    [self.delegate successEditStr:@"T"];
                    [self.tableV reloadData];
                }else {
                    [[MessShowView share] showWithMess:dict[@"m"] login:NO];
                }
            }];
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
